﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace DisposeUnmanagedObject.Demo
{
    public class CacheHandel : IDisposable
    {
        private bool _isDispose = false;
        protected ConnectionMultiplexer redisConnect;
        protected IDatabase redisContext;
        protected ConfigurationOptions connectConfig = new ConfigurationOptions();

        public CacheHandel() 
        {
            connectConfig.SslHost = "114.115.242.152:6379";
            redisConnect = ConnectionMultiplexer.Connect(connectConfig);
            redisContext = redisConnect.GetDatabase();
        }

        public void AddStringKeyValue(string key,string value) 
        {
            if(!_isDispose)
            redisContext.StringSet(key, value);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected void Dispose(bool disposing) 
        {
            if (!_isDispose)//是否以回收
            {
                if (disposing)//是否为Dispose调用
                {
                    //需要Dispose()调用销毁的资源
                    redisConnect?.Dispose();
                }

                //需要构析函数调用销毁的资源
                _isDispose = true;
            }
        }

        ~CacheHandel() 
        {
            Dispose(false);
        }

    }
}
